import {createRouter, createWebHistory} from 'vue-router'
import {useUserStore} from '@/store'

// 路由配置
const routes = [
    {
        path: '/',
        name: 'Layout',
        component: () => import('@/layout/index.vue'),
        redirect: '/home',
        children: [
            {
                path: '/home',
                name: 'Home',
                component: () => import('@/views/Home.vue'),
                meta: {
                    title: '首页',
                    requiresAuth: false
                }
            },
            {
                path: '/category',
                name: 'Category',
                component: () => import('@/views/Category.vue'),
                meta: {
                    title: '分类',
                    requiresAuth: false
                }
            },
            {
                path: '/cart',
                name: 'Cart',
                component: () => import('@/views/Cart.vue'),
                meta: {
                    title: '购物车',
                    requiresAuth: true
                }
            },
            {
                path: '/profile',
                name: 'Profile',
                component: () => import('@/views/Profile.vue'),
                meta: {
                    title: '个人中心',
                    requiresAuth: true
                }
            },
            {
                path: '/search',
                name: 'SearchResult',
                component: () => import('@/views/SearchResult.vue'),
                meta: {
                    title: '搜索结果',
                    requiresAuth: false
                }
            },
            {
                path: '/order/:orderId/select',
                name: 'CommentSelect',
                component: () => import('@/views/CommentSelect.vue'),
                meta: {
                    title: '选择评价商品',
                    requiresAuth: true
                }
            },
            // 移除评价全部商品的路由，只保留单个商品评价
            {
                path: '/comment/create',
                name: 'CommentCreateSingle',
                component: () => import('@/views/CommentCreate.vue'),
                meta: {
                    title: '评价商品',
                    requiresAuth: true
                }
            },
            {
                path: '/product/:id',
                name: 'ProductDetail',
                component: () => import('@/views/ProductDetail.vue'),
                meta: {
                    title: '商品详情',
                    requiresAuth: false
                }
            },
            // 移除独立的商品评价路由，评价功能统一通过订单完成后进行
            {
                path: '/checkout',
                name: 'Checkout',
                component: () => import('@/views/Checkout.vue'),
                meta: {
                    title: '确认订单',
                    requiresAuth: true
                }
            },
            {
                path: '/orders',
                name: 'OrderList',
                component: () => import('@/views/OrderList.vue'),
                meta: {
                    title: '我的订单',
                    requiresAuth: true
                }
            },
            {
                path: '/order/:id',
                name: 'OrderDetail',
                component: () => import('@/views/OrderDetail.vue'),
                meta: {
                    title: '订单详情',
                    requiresAuth: true
                }
            },
            {
                path: '/payment/:orderId',
                name: 'Payment',
                component: () => import('@/views/Payment.vue'),
                meta: {
                    title: '订单支付',
                    requiresAuth: true
                }
            }
        ]
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login.vue'),
        meta: {
            title: '登录',
            requiresAuth: false
        }
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('@/views/Register.vue'),
        meta: {
            title: '注册',
            requiresAuth: false
        }
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        redirect: '/home'
    }
]

// 创建路由实例
const router = createRouter({
    history: createWebHistory(),
    routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()
    const token = userStore.token

    // 设置页面标题
    if (to.meta.title) {
        document.title = `${to.meta.title} - Easy Mart`
    }

    // 如果访问登录/注册页面且已登录，重定向到首页
    if ((to.path === '/login' || to.path === '/register') && token) {
        next('/home')
        return
    }

    // 如果需要认证且未登录，重定向到登录页
    if (to.meta.requiresAuth && !token) {
        next('/login')
        return
    }

    // 如果已登录但用户信息为空，自动获取用户信息
    if (token && !userStore.userInfo) {
        try {
            await userStore.fetchUserInfo()
        } catch (error) {
            console.error('自动获取用户信息失败:', error)
            // 如果获取用户信息失败，可能token已过期，清除登录状态
            if (error.response?.status === 401) {
                userStore.logout()
                if (to.meta.requiresAuth) {
                    next('/login')
                    return
                }
            }
        }
    }

    next()
})

export default router
